<?php

// +----------------------------------------------------------------------
// | 行为事件
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\ucenter;

use app\common\event\Base;
use app\model\ucenter\IpPool as IpPoolModel;
use app\model\ucenter\User as UserModel;
use think\Exception;
use think\facade\Lang;
use yicmf\tools\HttpService;

class IpPool extends Base
{


    /**
     * 通用更新方法
     * @param array   $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function update($param, $user = null)
    {
        try {
            if (empty($param)) {
                throw new Exception(Lang::get('__data_format_error_'));
            }
            if (!empty($param['id'])) {
                // 更新操作
                $result = IpPoolModel::update($param, ['id'=>$param['id']]);
            } else { // 新增
                $result = IpPoolModel::create($param);
            }
            $data['code'] = 0;
            $data['data'] = $result;
            $data['message'] = '操作成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 获取IP信息
     * @param string|null $ip
     * @return array
     */
    public function info( $ip = null,$find=false)
    {
        try {
            if (empty($ip))
            {
                $ip = $this->request->ip();
            }
            $info = IpPoolModel::where('status', 1)
                ->where('ip', $ip)
                ->cache(true,60)
                ->find();
            if (!$info) {
                // 添加
                if ($find)
                {
                    $info = self::findInfo($ip);
                }
                $info['ip'] = $ip;
                $info = IpPoolModel::create($info);
            }
            $data['code'] = 0;
            $data['data'] = $info;
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;

    }

    public static function findInfo($ip)
    {
        //https://ipinfo.io/182.124.3.138/json 每月5w
        //https://ipapi.co/125.40.177.105/json/ 每天1000，带经纬度
        //http://ip-api.com/json/117.136.12.79?lang=zh-CN 每分钟45次限制
//                $re= HttpService::get('http://ip-api.com/json/182.124.3.138?lang=zh-CN');
//			$re = HttpService::get('http://ip-api.com/json/125.40.177.105?lang=zh-CN');
        //直接调用即可【没有频率限制】：https://ip.useragentinfo.com/json?ip=117.136.12.79
        //http://whois.pconline.com.cn/ipJson.jsp?ip=117.136.12.79&json=true
//            $data = HttpService::get('http://ip-api.com/json/'. $ip.'?lang=zh-CN' );
//        header('Content-type:text/html;charset=utf-8');
        $info = HttpService::get('http://whois.pconline.com.cn/ipJson.jsp?ip='. $ip.'&json=true' );
//        mb_internal_encoding('UTF-8');
        $str = trim(iconv('GB2312', 'UTF-8', $info['content']));
        $info = json_decode($str,true);
        if (!empty($info['pro']))
        {
            $data['region_id'] = $info['proCode'];
            $data['region_name'] = $info['pro'];
            $data['city'] = $info['city'];
            $data['city_id'] = $info['cityCode'];
        }else{
            $data['country'] = 'no';
        }
//            $info = HttpService::get('http://ip-api.com/json/'. $ip.'?lang=zh-CN' );
//            if (isset($info['content']['status']) && 'success' == $info['content']['status'])
//            {
//                $data['country'] = $info['content']['country'];
//                $data['country_code'] = $info['content']['countryCode'];
//                $data['region'] = $info['content']['region'];
//                $data['region_name'] = $info['content']['regionName'];
//                $data['city'] = $info['content']['city'];
//                $data['lat'] = $info['content']['lat'];
//                $data['lon'] = $info['content']['lon'];
//                $data['zip'] = $info['content']['zip'];
//                $data['timezone'] = $info['content']['timezone'];
//            }else{
//                $data['country'] = 'no';
//            }
        return $data;
    }
    /**
     * 同步IP信息
     * @param string $ip
     * @return array
     */
    public static function task()
    {
        $data = IpPoolModel::whereRaw('create_time = update_time')->find();
        if ($data)
        {
            $update = self::findInfo($data['ip']);
            $update['update_time'] = time_format();
            $data->save($update);
        }

    }
}
